package com.newlink.building.userinfo.activity

import android.Manifest
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.FileUtils
import android.text.TextUtils
import android.view.View
import android.webkit.MimeTypeMap
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.newlink.building.common_base.activities.Base_ImageCropActivityNL
import com.newlink.building.common_base.activities.Base_ImageSelectActivityNL
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.constant.Base_RouterPath
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.AvatarResponse
import com.newlink.building.common_base.model.bean.UpdateAvatarBean
import com.newlink.building.common_base.model.bean.UserInfoResp
import com.newlink.building.common_base.utils.DialogUtil
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.logDebug
import com.newlink.building.common_base.widget.CustomInputDialog
import com.newlink.building.common_base.widget.CustomMessageDialog
import com.newlink.building.manager.Module_Phone_VoipController
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.databinding.ActivityAccountInformationBinding
import com.newlink.building.userinfo.mvp.Module_UserInfo_AccountInformationPresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_AccountInformationContract
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationHelper
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationInvoker
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.jetbrains.anko.image
import org.jetbrains.anko.toast
import java.io.File
import java.io.FileOutputStream
import java.net.URI
import java.net.URISyntaxException
import kotlin.random.Random

/**
 * @author wangyang
 * @date 2022/9/16
 * @description 我的——账户信息页面
 */
class Module_UserInfo_AccountInformationActivityNL :
    NL_BaseMvpActivity<Module_UserInfo_AccountInformationContract.View, Module_UserInfo_AccountInformationContract.Presenter>(),
    Module_UserInfo_AccountInformationContract.View, View.OnClickListener {

    private val TAG: String = "fvl_dbg"

    private val mDialog by lazy {
        DialogUtil.getWaitDialog(this)
    }

    private lateinit var mBinding: ActivityAccountInformationBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityAccountInformationBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {
    }

    override fun onResume() {
        super.onResume()
        updateUserInfoDisplay(userInfoResp)
    }

    private fun updateUserInfoDisplay(userInfoResp: UserInfoResp) {
        mBinding.tvUsername.text = userInfoResp.name
        mBinding.tvEmail.text = userInfoResp.email
        if (TextUtils.isEmpty(userInfoResp.mobile)) {
            mBinding.tvPhone.visibility = View.GONE
        } else {
            mBinding.tvPhone.text = userInfoResp.mobile
            mBinding.tvPhone.visibility = View.VISIBLE
        }
    }

    override fun initView() {
        super.initView()
        // 账户信息页面初始化时的混淆
        Module_Obfuscation_ObfuscationHelper.onMethodEnter("AccountInformationActivity", "initView")
        Module_Obfuscation_ObfuscationInvoker.invokeRandom(userInfoResp.hashCode())

        findViewById<TextView>(R.id.tv_title_bar_center).text =
            resources.getText(R.string.account_information_title)
        mBinding.rlHead.visibility = View.GONE
        mBinding.rlHead.setOnClickListener(this)
        mBinding.rlUsername.setOnClickListener(this)
        mBinding.rlPhone.setOnClickListener(this)
        mBinding.rlChangePassword.setOnClickListener(this)
        mBinding.btnCancel.setOnClickListener(this)
        if (userInfoData.userCategory == 3) {
            mBinding.btnCancel.visibility = View.GONE
            mBinding.rlPhone.visibility = View.GONE
            mBinding.dividerPhone.visibility = View.GONE
        }

        mPresenter?.getUserInfo(accessToken, userId)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        for ((index, requestResult) in grantResults.withIndex()) {
            logDebug<Module_UserInfo_AccountInformationActivityNL>("requestResult[$index]:${requestResult == PackageManager.PERMISSION_GRANTED}")
        }
    }

    override fun createPresenter(): Module_UserInfo_AccountInformationContract.Presenter {
        return Module_UserInfo_AccountInformationPresenter()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val bindResult = intent?.getIntExtra("bindResult", 0)
        bindResult?.let {
            if (it == 1) {
                NLog.e("[jake] update user info ....")
                mPresenter?.getUserInfo(accessToken, userId)
            }
        }
    }

    override fun getUserInfoNewSuccess(userInfo: UserInfoResp) {
        logDebug<Module_UserInfo_AccountInformationActivityNL>("getUserInfoNewSuccess new:${userInfo.name} old:${userInfoResp.name}")
        if (userInfo.name != userInfoResp.name) {
            Module_Phone_VoipController.get().updateDisplayName(userInfo.name)
        }
        userInfoResp = userInfo
        updateUserInfoDisplay(userInfo)
    }

    override fun getUserInfoFail() {
        logDebug<Module_UserInfo_AccountInformationActivityNL>("  getUserInfoFail !!!")
        mBinding.ivHead.image = getDrawable(R.mipmap.personal_head)
        mBinding.tvUsername.text = ""
        mBinding.tvEmail.text = ""
        mBinding.tvPhone.text = ""
        mBinding.tvPhone.visibility = View.GONE
    }

    override fun setUserInfoSuccess() {
        showToast(getString(R.string.default_change_success))
        mPresenter?.getUserInfo(accessToken, userId)

        if (mDialog.isShowing) {
            mDialog.dismiss()
        }
    }

    override fun setUserInfoFail() {
        showToast(getString(R.string.default_change_fail))
    }

    override fun uploadAvatarSuccess(avatarResponse: AvatarResponse) {
        toast("uploadAvatarSuccess")
        logDebug<Module_UserInfo_AccountInformationActivityNL>("[AccountInfoActivity]  uploadAvatarSuccess::::> $avatarResponse")

        val userInfo = UpdateAvatarBean().apply {
            picture = avatarResponse.url
        }

        logDebug<Module_UserInfo_AccountInformationActivityNL>("[AccountInfoActivity]  准备setUserinfo::::> ${userInfo}")
        mPresenter?.syncUserInfo(accessToken, userInfo)

    }

    override fun uploadAvatarFail() {
        toast("uploadAvatarFail")
        logDebug<Module_UserInfo_AccountInformationActivityNL>("[AccountInfoActivity]  上传头像失败::::")
        mDialog.dismiss()
    }

    override fun deleteAccountSuccess() {
        showToast(getString(R.string.default_delete_success))
        cleanUserInfo()
        Module_Phone_VoipController.get().delete()
        ARouter.getInstance().build(Base_RouterPath.PATH_LOGIN)
            .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
            .navigation()
        finish()
    }

    fun cleanUserInfo() {
        emailAccount = ""
        pwdSaved = ""
        isLogin = false
    }

    override fun deleteAccountFail() {
        showToast(getString(R.string.default_delete_fail))
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.rl_head -> {
                if (!checkMyPermission()) {
//                    requestPermissions(mPermissionList, 11011)
                } else {
                    Base_ImageSelectActivityNL.start(
                        this,
                        object : Base_ImageSelectActivityNL.OnPhotoSelectListener {

                            override fun onSelected(data: MutableList<String>) {
                                // 裁剪头像
                                cropImageFile(File(data[0]))
                            }
                        })
                }
            }

            R.id.rl_username -> {
                //修改用户名
                val customInputDialog = CustomInputDialog(this)
                customInputDialog.setTitle(getString(R.string.account_information_username))
                    .setText(mBinding.tvUsername.text as String)
                    .setNegativeButton(listener = object : CustomInputDialog.OnClickListener {
                        override fun onClick(type: Int, inputText: String) {
                            customInputDialog.dismiss()
                        }

                    }).setPositiveButton(listener = object : CustomInputDialog.OnClickListener {
                        override fun onClick(type: Int, inputText: String) {
                            if (inputText.isNotEmpty()) {
                                mPresenter?.setUserInfo(accessToken, "$userId", inputText)
                                customInputDialog.dismiss()
                            } else {
                                showToast(getString(R.string.account_information_username_no_empty))
                            }
                        }
                    })
                customInputDialog.show()
            }

            R.id.rl_change_password -> {
                //修改密码
                startActivity(Intent(this, Module_UserInfo_AccountInformationChangePasswordActivityNL::class.java))
            }

            R.id.btn_cancel -> {

                val message =
                    if (isPrimaryAccount) getString(R.string.account_information_delete_account_content_primary) else getString(
                        R.string.account_information_delete_account_content
                    )
                CustomMessageDialog(this).setTitle(getString(R.string.account_information_delete_account))
                    .setMessage(message)
                    .setPositiveButton { dialog ->
                        mPresenter?.deleteAccount(accessToken, "$userId", isPrimaryAccount)
                        dialog.dismiss()
                    }.setNegativeButton { dialog -> dialog.dismiss() }.show()
            }
        }
    }

    /**
     * 校验权限
     */
    private fun checkMyPermission(): Boolean {
        return if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
//            && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
//            && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
        ) {
            logDebug<Module_UserInfo_AccountInformationActivityNL>("checkSelfPermission[true]")
            true
        } else {
            logDebug<Module_UserInfo_AccountInformationActivityNL>("checkSelfPermission[false]")
            false
        }
    }

    private fun cropImageFile(sourceFile: File) {
        Base_ImageCropActivityNL.start(this, sourceFile, 1, 1, object : Base_ImageCropActivityNL.OnCropListener {

            override fun onSucceed(fileUri: Uri, fileName: String) {
                val outputFile: File = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    uriToFileQ(this@Module_UserInfo_AccountInformationActivityNL, fileUri)!!
                } else {
                    try {
                        File(URI(fileUri.toString()))
                    } catch (e: URISyntaxException) {
                        e.printStackTrace()
                        File(fileUri.toString())
                    }
                }
                uploadImage(outputFile)
            }

            override fun onError(details: String) {
                uploadImage(sourceFile)
            }
        })
    }

    fun uploadImage(file: File) {
        logDebug<Module_UserInfo_AccountInformationActivityNL>("[wcnm]... upload picture ${file.absolutePath}")
        mDialog.show()

        val avatarUrl = Uri.fromFile(file)
        mBinding.ivHead?.let {
            Glide.with(this)
                .load(avatarUrl)
                .transform(MultiTransformation(CenterCrop(), CircleCrop()))
                .into(it)
        }

        val requestFile = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file)
        val body: MultipartBody.Part =
            MultipartBody.Part.createFormData("file", file.name, requestFile)
        mPresenter?.uploadAvatar2(accessToken, body)
    }

    @RequiresApi(Build.VERSION_CODES.Q)
    private fun uriToFileQ(context: Context, uri: Uri): File? =
        if (uri.scheme == ContentResolver.SCHEME_FILE)
            File(requireNotNull(uri.path))
        else if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
            //把文件保存到沙盒
            val contentResolver = context.contentResolver
            val displayName = "${System.currentTimeMillis()}${Random.nextInt(0, 9999)}.${
                MimeTypeMap.getSingleton()
                    .getExtensionFromMimeType(contentResolver.getType(uri))
            }"
            val ios = contentResolver.openInputStream(uri)
            if (ios != null) {
                File("${context.cacheDir.absolutePath}/$displayName")
                    .apply {
                        val fos = FileOutputStream(this)
                        FileUtils.copy(ios, fos)
                        fos.close()
                        ios.close()
                    }
            } else null
        } else null
}